package com.luo.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luo.dao.impl.SummaryDaoImpl;
import com.luo.model.*;
import com.luo.util.CountDown;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 功能：
 * 作者：Luo。
 * 日期：2024/3/22 10:38
 */
public class SummaryService {

	SummaryDaoImpl summaryDao = new SummaryDaoImpl();
	GoodService goodService = new GoodService();
	CartService cartService = new CartService();

	public Summary getSummary(List<Address> addresses, List<CartsVO> cartsVOS) {
		Summary summary = new Summary();
		summary.setGoodsCount(cartsVOS.size());
		// 计算订单总价格
		Double totalPrice = 0.0;
		// 计算订单的实价格
		Double totalPayPrice = 0.0;
		for (CartsVO c : cartsVOS) {
			totalPrice += c.getCount() * c.getGoodPrice();
			totalPayPrice += c.getCount() * c.getGoodPrice() * c.getGoodDiscount();
		}
		summary.setTotalPrice(totalPrice);
		summary.setTotalPayPrice(totalPayPrice);
		// 计算总折扣
		summary.setDiscountPrice(totalPrice - totalPayPrice);
		return summary;
	}

	// 提交订单
	public String SubmitOrderController(String addressId, String goods, String userId) {
		if (addressId == null || addressId.trim().isEmpty() || goods == null || goods.trim().isEmpty()) {
			return "-1";
		}
		HashMap<String, String> map = new HashMap<>();
		UUID uuid = UUID.randomUUID();
		String id = uuid.toString().replace("-", "").substring(0, 11);
		map.put("addressId", addressId);
		map.put("userId", userId);
		map.put("goods", goods);
		map.put("id", id);
		map.put("createTime", String.valueOf(new Date().getTime()));
		int i = summaryDao.SubmitOrderController(map);
		// 订单超时计算
		CountDown.countDownTime(id, new SummaryService());
		if (i > 0) {
			return id;
		}
		return "-2";
	}

	public Summary querySummaryById(String id) {
		Summary summary = summaryDao.querySummaryById(id);
		return summary;
	}

	public int updateSummaryStatusIs2(String id) {
		int i = summaryDao.updateSummaryStatusIs2(id);
		return i;
	}

	// 根据订单商品计算订单信息
	public SummaryInfoVO getSummaryInfo(Summary summary) throws JsonProcessingException {
		SummaryInfoVO summaryInfoVO = new SummaryInfoVO();
		summaryInfoVO.setGoodsNames("");
		summaryInfoVO.setMoneyCount(0.0);
		String goods = summary.getGoods();
		// 初始化ObjectMapper
		ObjectMapper objectMapper = new ObjectMapper();
		// 将JSON字符串转换为List<Map<String, Integer>>
		List<Map<String, Integer>> list = objectMapper.readValue(goods, new TypeReference<List<Map<String, Integer>>>() {
		});
		for (Map<String, Integer> map : list) {
			// 遍历计算所有商品的价格
			Integer id = map.get("id");
			Integer count = map.get("count");
			if (id != null) {
				// 根据购物车获取商品id
				Carts cart = cartService.queryCartsByCartsId(String.valueOf(id));
				// 获取商品 价格 和 折扣
				Goods goods1 = goodService.queryGoodBy(cart.getGoodId());
				Double disCountEnd = Double.valueOf(goods1.getDiscount()) / 10;
				Double price = Double.valueOf(goods1.getPrice());
				if (disCountEnd > 0.0) {
					BigDecimal bigPrice = new BigDecimal(price);
					BigDecimal bigDisCountEnd = new BigDecimal(disCountEnd);
					BigDecimal bigCount = new BigDecimal(count);
					goods1.setOldPrice(String.valueOf(bigPrice.multiply(bigDisCountEnd).multiply(bigCount).setScale(2, RoundingMode.HALF_UP)));
				} else {
					goods1.setOldPrice(String.format("%.2f", price * count));
				}
				// 计算商品的总价
				summaryInfoVO.setMoneyCount(summaryInfoVO.getMoneyCount() + Double.valueOf(goods1.getOldPrice()));
				summaryInfoVO.setGoodsNames(summaryInfoVO.getGoodsNames() + " " + goods1.getName());
			}
		}
		BigDecimal moneyCount = new BigDecimal(summaryInfoVO.getMoneyCount()).setScale(2, RoundingMode.HALF_UP);
		summaryInfoVO.setMoneyCount(moneyCount.doubleValue());
		return summaryInfoVO;
	}

	// 设置订单的状态
	public int updateSummaryStatus(String id, String status) {
		HashMap<String, String> map = new HashMap<>();
		map.put("id", id);
		map.put("status", status);
		int i = summaryDao.updateSummaryStatus(map);
		return i;
	}

	// 分页条件查询订单
	public List<Order> queryOrders(String id, String orderState, String page, String pageSize) {
		Map<String, Object> map = new HashMap<>();
		if ("".equals(orderState)) {
			orderState = null;
		}
		if (page.isEmpty() || pageSize.isEmpty()) {
			page = null;
			pageSize = null;
		}
		map.put("id", id);
		map.put("status", orderState);
		map.put("page", (Integer.valueOf(page) - 1) * Integer.valueOf(pageSize));
		map.put("pageSize", Integer.valueOf(pageSize));
		List<Order> summaries = summaryDao.queryOrders(map);
		return summaries;
	}

	// 查询条数
	public int queryOrdersCount(String id, String orderState, String page, String pageSize) {
		Map<String, Object> map = new HashMap<>();
		if ("".equals(orderState)) {
			orderState = null;
		}
		if (page.isEmpty() || pageSize.isEmpty()) {
			page = null;
			pageSize = null;
		}
		map.put("id", id);
		map.put("status", orderState);
		map.put("page", Integer.valueOf(page));
		map.put("pageSize", Integer.valueOf(pageSize));
		int count = summaryDao.queryOrdersCount(map);
		return count;
	}

		// 返回查询结果
	public QueryOrdersVO queryOrdersResult(List<Order> orders,int counts) throws JsonProcessingException {

		// 获取结果中的商品
		for (Order o : orders) {
			String jsonString = o.getGoods();
			ObjectMapper objectMapper = new ObjectMapper();
			List<Map<String, Integer>> list = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, Integer>>>() {
			});
			List<Goods> goodsList = new ArrayList<>();
			for (Map<String, Integer> map : list) {
				// 遍历计算所有商品的价格
				Integer id = map.get("id");
				Integer count = map.get("count");
				if (id != null) {
					// 根据购物车获取商品id
					Carts cart = cartService.queryCartsByCartsId(String.valueOf(id));
					// 获取商品信息
					if (cart != null && cart.getGoodId() != null && !cart.getGoodId().isEmpty()){
						Goods goods1 = goodService.queryGoodBy(cart.getGoodId());
						goods1.setCount(count);
						goodsList.add(goods1);
					}
				}
			}
			o.setGoodsList(goodsList);
		}
		QueryOrdersVO queryOrdersVO = new QueryOrdersVO();
		queryOrdersVO.setOrders(orders);
		queryOrdersVO.setCount(counts);
		return queryOrdersVO;
	}
}
